package com.jasperframework.boot.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.*;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

/**
  * <p>  </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */
public class RSAUtil {

    private static final String ALGORITHM = "RSA";

    private static final Integer KEY_SIZE = 512*8;

    public static final String CRYPT_KEY = "*(Xd$tb1"; //指定8位数的密钥   *(Xd$tb1

    private static final String  PUBLICKEY_KEYSTORE = "d:/publickey.keystore";

    private static final String  PRIVATEKEY_KEYSTORE = "d:/privatekey.keystore";

    private static final Logger logger = LoggerFactory.getLogger(RSAUtil.class);

    /**
     *  @Author daizhao
     *  @Date 2018-4-3 11:18
     *  @Params []
     *  @Return void
     *  @Info  生成密钥对
     */
    public static void generateKeyPair() throws Exception{
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(KEY_SIZE, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        /** 用对象流将生成的密钥写入文件 */
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLICKEY_KEYSTORE));
        ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATEKEY_KEYSTORE));
        oos1.writeObject(publicKey);
        oos2.writeObject(privateKey);
        /** 清空缓存，关闭文件输出流 */
        oos1.close();
        oos2.close();
    }

    /**
     *  @Author daizhao
     *  @Date 2018-4-8 11:42
     *  @Params [source：要进行加密的内容, privateKey：加密的私钥]
     *  @Return java.lang.String
     *  @Info  RSA加密算法
     */
    public static String encrypt(String source, String privateKey) throws Exception{
        /** 将文件中的私钥对象读出 */
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(privateKey));
        Key key = (Key) ois.readObject();
        ois.close();
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return BASE64Utils.getEncodeBase64(b1);
    }

    /**
     *  @Author daizhao
     *  @Date 2018-4-8 11:45
     *  @Params [cryptograph：密文, publicKey：公钥]
     *  @Return java.lang.String
     *  @Info  RSA解密算法
     */
    public static String decrypt(String cryptograph, String publicKey) throws Exception{
        /** 将文件中的公钥对象读出 */
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(publicKey));
        Key key = (Key) ois.readObject();
        /** 得到Cipher对象对已用私钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] b1 = BASE64Utils.decodeBase64(cryptograph);
        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }

    /**
     *  @Author daizhao
     *  @Date 2018-4-9 10:16
     *  @Params [desKey]
     *  @Return void
     *  @Info   加密和解密desKey
     */
    public static String handleAction(String desKey){
        try {
            generateKeyPair();
            String encryptStr = encrypt(desKey, PRIVATEKEY_KEYSTORE);
            String decryptStr = decrypt(encryptStr, PUBLICKEY_KEYSTORE);
            logger.info("desKey：[" +  desKey + "]");
            logger.info("encryptStr：[" + encryptStr  + "]");
            logger.info("decryptStr：[" + decryptStr  + "]");
            return encryptStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String desKey = null;
        try {
            //采用base64编码格式
            desKey = BASE64Utils.getEncodeBase64(CRYPT_KEY, null);
            // 自定义字符串 desKey = CRYPT_KEY;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        handleAction(desKey);
    }
}
